/*
 * UDPPinger.cpp
 *
 *  Created on: 16.03.2011
 *      Author: niea
 */

#include "UDPPinger.hpp"
#include "../common/Utils.hpp"
#include "../rapidxml-1.13/rapidxml.hpp"
#include "../rapidxml-1.13/rapidxml_print.hpp"
#include "../common/ClientEntry.hpp"
#include "../common/MyIP.hpp"

#include <cstring>

using namespace efs;
using namespace rapidxml;

UDPPinger::UDPPinger(Settings const& settings)
	: UDPThread(settings)
{
}

void UDPPinger::threadProc()
{
	ping();
}

void UDPPinger::ping()
{
	int len = 1;
	setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, &len, sizeof(len));

	struct sockaddr_in sockaddr;
	memset(&m_sockaddr, 0, sizeof(sockaddr));
	sockaddr.sin_family = AF_INET;
	sockaddr.sin_port = htons (m_settings.udp_port);
	sockaddr.sin_addr.s_addr = htonl(0xFFFFFFFF);

	while (1)
	{
		std::string msg = m_settings.my_net_settings.getXMLString();
		//pantheios::log_DEBUG("[UDPPinger]: Pinging");

        if (sendto(m_socket, msg.c_str(), msg.length(), 0, (struct sockaddr *) &sockaddr,
        		sizeof(sockaddr)) != msg.length())
        {
        	pantheios::log_ERROR("[UDPPinger]: Mismatch in number of sent bytes");
        }

		for(int i = 0; i < m_settings.ping_period * 100; ++i)
		{
			usleep(10000);
			if (m_stop_req)
			{
				pantheios::log_DEBUG("[UDPPinger]: Exit on user command");
				closeAll();
				return;
			}
		}

	}
}
